package com.yueguang.springai.openai.controller;

import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionContentPart;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import com.volcengine.tos.TOSV2;
import com.volcengine.tos.comm.common.ACLType;
import com.volcengine.tos.model.object.*;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class ChatController {

    @Resource
    private ArkService arkService;
    @Resource
    private TOSV2 tosV2;
    @Value("${doubao.tos.endpoint}")
    private String endpoint;
    private static final String UPLOAD_DIR = "uploads/"; // 上传目录
    String bucketName = "zy-student-error";

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("msg") String msg) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择一个文件进行上传", HttpStatus.BAD_REQUEST);
        }

        try {
            byte[] dataInBytes = file.getBytes();
            String objectKey = UPLOAD_DIR + file.getOriginalFilename();
            ByteArrayInputStream stream = new ByteArrayInputStream(dataInBytes);
            PutObjectInput putObjectInput = new PutObjectInput()
                    .setBucket(bucketName).setKey(objectKey).setContent(stream);
            PutObjectOutput output = tosV2.putObject(putObjectInput);
            System.out.println("putObject succeed, object's etag is " + output.getEtag());
            System.out.println("putObject succeed, object's crc64 is " + output.getHashCrc64ecma());
            // 授予 objectKey 对象公共读权限
            PutObjectACLInput input = new PutObjectACLInput().setAcl(ACLType.ACL_PUBLIC_READ)
                    .setBucket(bucketName).setKey(objectKey);
            PutObjectACLOutput output2 = tosV2.putObjectAcl(input);
            System.out.println("putObjectAcl succeed."+output2.toString());


            System.out.println("----- image input -----");
            String bucketURL = "https://" + bucketName + "." + endpoint + "/" ;
            String ImageURL = bucketURL+ objectKey;
            System.out.println("ImageURL: "+ImageURL);
            final List<ChatMessage> messages = new ArrayList<>();
            final List<ChatCompletionContentPart> multiParts = new ArrayList<>();
            multiParts.add(ChatCompletionContentPart.builder().type("text").text(
                    msg
            ).build());
            multiParts.add(ChatCompletionContentPart.builder().type("image_url").imageUrl(
                    new ChatCompletionContentPart.ChatCompletionContentPartImageURL(
                            ImageURL
                    )
            ).build());
            final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER)
                    .multiContent(multiParts).build();
            messages.add(userMessage);

            ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                    .model("ep-20250110150212-jrcfq")
                    .messages(messages)
                    .build();

            arkService.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> {
                String messageContent = choice.getMessage().getContent().toString();
                System.out.println(messageContent);
                ChatMessage newMessage = new ChatMessage();
                newMessage.setContent(messageContent);
                messages.add(newMessage);
            });

            // 将 messages 转换为字符串表示
            String responseContent = messages.stream()
                    .map(message -> message.getContent().toString())  // 显式转换为 String
                    .collect(Collectors.joining("\n"));

            // shutdown service after all requests is finished
            arkService.shutdownExecutor();
            return new ResponseEntity<>("文件上传成功: " + file.getOriginalFilename() + "\n"+responseContent , HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件上传失败: " + file.getOriginalFilename(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/sendMsgToDS")
    public ResponseEntity<String> sendMsgToDS(@RequestParam("msg") String msg) {
        try {

            System.out.println("\n----- streaming request -----");
            final List<ChatMessage> messages = new ArrayList<>();
            final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content("AI 人工智能助手").build();
            final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(msg).build();
            messages.add(systemMessage);
            messages.add(userMessage);

            ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                    .model("ep-20250206111322-k7t4p")
                    .messages(messages)
                    .build();

            arkService.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> {
                String messageContent = choice.getMessage().getContent().toString();
                System.out.println(messageContent);
                ChatMessage newMessage = new ChatMessage();
                newMessage.setContent(messageContent);
                messages.add(newMessage);
            });
            // shutdown service after all requests is finished
            arkService.shutdownExecutor();
            String responseContent = messages.stream()
                    .map(message -> message.getContent().toString())  // 显式转换为 String
                    .collect(Collectors.joining("\n"));
            return new ResponseEntity<>("回答结果: " +responseContent , HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>("回答结果: " +e , HttpStatus.OK);
        }
    }

}

